﻿using Hardware.Reactor.Base;
using Hardware.Reactor.Base.Model;
using Hardware.Reactor.Base.Setting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Hardware.Reactor.Default
{
    /// <summary>
    /// 1号温度采集模块
    /// </summary>
    public class Temp1Reader : TempReaderBase, ITemp1Reader
    {
        public override bool DoInit()
        {
            bool result = false;

            try
            {
                if (ConnectionMode == ConnectionMode.串口)
                {
                    if (serialPort == null)
                    {
                        serialPort = new System.IO.Ports.SerialPort(provider.ReactorConfig.Temp1ReaderPortName, provider.ReactorConfig.Temp1ReaderBaudRate); ;
                        serialPort.Open();
                    }

                    if (serialPort.IsOpen)
                    {
                        Initialized = serialPort.IsOpen;
                        Connected = serialPort.IsOpen;
                    }
                    else
                    {
                        return false; 
                    }
                }
                else
                {
                    if (tcpClient == null)
                    {
                        tcpClient = new System.Net.Sockets.TcpClient();
                        tcpClient.ConnectAsync(provider.ReactorConfig.Temp1ReaderIP, provider.ReactorConfig.Temp1ReaderPort).Wait(3000);
                    }

                    if(tcpClient.Connected)
                    {
                        Initialized = tcpClient.Connected;
                        Connected = tcpClient.Connected;
                    }
                    else
                    {
                        tcpClient = null;
                        return result;
                    }
                }
            }
            catch(Exception ex)
            {
                Message = $"1号温度采集模块连接失败:{ex.Message}";
                return result;
            }

            return true;
        }
    }
}
